<template>
  <el-dialog
    :visible.sync="visible"
    :title="getFrameTitle"
    custom-class="change-bind-email-dialog"
    width="25%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @open="onOpen"
    @close="onClose"
  >
    <div class="replace_box">
      <div class="steps_box">
        <el-steps class="replaceStep" :active="currStep" align-center>
          <el-step v-for="(item, index) in getReplaceStep" :key="index" :title="item.title" />
        </el-steps>
      </div>
      <div class="form_box">
        <el-form v-if="currStep === '1'" ref="formRef" label-width="80px" :rules="formRules">
          <el-form-item :label="getLabel" prop="old_email_phone" class="phone_item">
            <el-input
              v-if="caminho === 'email'"
              :disabled="true"
              v-model="formModel.old_email_phone"
              maxlength="100"
            />

            <div class="phone_box" v-if="caminho === 'mobile'" :class="['phone_box', getBorder]">
              <div class="ease_animation" style="width: 90px">
                <el-select v-model="phoneCode" slot="prepend" :disabled="true" style="width: 90px">
                  <el-option
                    :label="item.paramValue"
                    :value="item.id"
                    v-for="(item, index) in phoneCodeList"
                    :key="index"
                  ></el-option>
                </el-select>
              </div>
              <el-input
                :disabled="true"
                v-model="formModel.old_email_phone"
                :placeholder="getPrompt"
                @blur="emailBlur"
                @focus="emailFocus"
                @input="emailChange"
                maxlength="100"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item
            :label="$t('login.mima8')"
            prop="verificar_code"
            class="formItem formItem_code"
          >
            <el-input
              v-model="formModel.verificar_code"
              :placeholder="$t('personInfo.xinxi32')"
              maxlength="100"
            />
            <span v-if="!isShow" class="code_btn" @click="getValidCode">{{ buttonName }}</span>
            <span v-if="isShow" class="code_btn">{{ buttonName }}</span>
          </el-form-item>
        </el-form>

        <el-form v-if="currStep === '2'" ref="formRef" label-width="80px" :model="formModel">
          <el-form-item :label="getLabel" prop="email_phone" class="phone_item">
            <el-input v-if="caminho === 'email'" v-model="formModel.email_phone" maxlength="100" />

            <div class="phone_box" v-if="caminho === 'mobile'" :class="['phone_box', getBorder]">
              <div class="ease_animation" style="width: 90px">
                <el-select v-model="phoneCode" slot="prepend" style="width: 90px">
                  <el-option
                    :label="item.paramValue"
                    :value="item.id"
                    v-for="(item, index) in phoneCodeList"
                    :key="index"
                  ></el-option>
                </el-select>
              </div>
              <el-input
                v-model="formModel.email_phone"
                :placeholder="getPrompt"
                @blur="emailBlur"
                @focus="emailFocus"
                @input="emailChange"
                maxlength="100"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item :label="$t('login.mima8')" prop="code" class="formItem formItem_code">
            <el-input
              v-model="formModel.code"
              :placeholder="$t('personInfo.xinxi32')"
              maxlength="100"
            />
            <span v-if="!isShow" class="code_btn" @click="getValidCode">{{ buttonName }}</span>
            <span v-if="isShow" class="code_btn">{{ buttonName }}</span>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- <el-form ref="formRef" :model="formModel" :rules="formRules">
      <el-form-item label="" prop="email">
        <el-input v-model="formModel.email" style="width: 320px" />
      </el-form-item>
      <el-form-item label="" prop="code" class="formItem formItem_code">
        <el-input
          v-model="formModel.code"
          style="width: 320px"
          :placeholder="$t('personInfo.xinxi32')"
        />
        <span v-if="!isShow" class="code_btn" @click="getValidCode">{{ buttonName }}</span>
        <span v-if="isShow" class="code_btn">{{ buttonName }}</span>
      </el-form-item>
      <el-form-item label="" prop="password">
        <el-input
          v-model="formModel.password"
          style="width: 320px"
          :placeholder="$t('personInfo.xinxi26')"
        />
      </el-form-item>
    </el-form> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">{{ $t('personInfo.xinxi34') }}</el-button>
        <el-button type="primary" @click="bindEmail">{{ $t('add.add30') }} </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { isEmail, isMobile } from '@/utils/validate';

export default {
  name: 'ChangeBindEmail',
  model: {
    prop: 'modelValue',
    event: 'update:modelValue',
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    caminho: {
      type: String,
      default: '',
    },
    old_email_phone: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      // 手机号输入框是否点击过
      isClick: false,
      // 定义变量确定是否聚焦
      isFocus: false,
      // 手机号或者邮箱是否合法
      phoneLegal: true,
      // 定义区号是否出现
      isShowAreaCode: false,
      clickCount: 0,
      phoneCodeList: [],
      phoneCode: '85',

      currStep: '1',
      replaceStep: [
        // {
        //   title: this.$t('personInfo.xinxi60'),
        // },
        // {
        //   title:
        //     this.caminho === 'mobile'
        //       ? this.$t('personInfo.xinxi61')
        //       : this.$t('personInfo.xinxi56'),
        // },
      ],
      formModel: {
        old_email_phone: '',
        verificar_code: '',
        email_phone: '',
        code: '',
      },
      count: 60,
      isShow: false,
      buttonName: this.$t('add.add026'),
      formRules: {
        email: [{ required: true, message: this.$t('zhuce.zhuce3'), trigger: 'blur' }],
        code: [{ required: true, message: this.$t('zhuce.zhuce9'), trigger: 'blur' }],
        password: [{ required: true, message: this.$t('zhuce.zhuce5'), trigger: 'blur' }],
      },
      timer: undefined,
    };
  },
  watch: {
    old_email_phone(val) {
      this.formModel.old_email_phone = this.old_email_phone;
    },
    currStep(val) {
      this.clickCount = 0;
    },
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(v) {
        this.$emit('update:modelValue', v);
      },
    },
    // 获取弹框标题
    getFrameTitle() {
      let title;
      if (this.caminho === 'mobile') {
        title = this.$t('personInfo.xinxi59');
      } else if (this.caminho === 'email') {
        title = this.$t('personInfo.xinxi56');
      }
      return title;
    },
    // 获取动态的表单label
    getLabel() {
      let label = '';
      if (this.caminho === 'mobile') {
        label = this.$t('zhuce.zhuce33');
      } else if (this.caminho === 'email') {
        label = this.$t('zhuce.zhuce2');
      }
      return label;
    },

    // 获取自定义输入框盒子的边框颜色
    getBorder: function () {
      let className = '';
      if (this.isClick) {
        if (this.isFocus) {
          if (this.phoneLegal) {
            className = 'curr_phone_box';
          } else {
            className = 'red_phone_box';
          }
        } else {
          if (this.phoneLegal) {
            className = 'curr_phone_box';
          } else {
            className = 'red_phone_box';
          }
        }
      }

      return className;
    },
    // 获取input的提示
    getPrompt() {
      if (this.caminho === 'email') {
        return this.$t('zhuce.zhuce3');
      } else if (this.caminho === 'mobile') {
        return this.$t('zhuce.zhuce34');
      }
    },
    getReplaceStep() {
      let list = [];
      if (this.caminho === 'email') {
        list = [
          {
            title: this.$t('personInfo.xinxi60'),
          },
          {
            title: this.$t('personInfo.xinxi56'),
          },
        ];
      } else if (this.caminho === 'mobile') {
        list = [
          {
            title: this.$t('personInfo.xinxi61'),
          },
          {
            title: this.$t('personInfo.xinxi59'),
          },
        ];
      }
      return list;
    },
  },
  created() {
    this.getPhoneArea();
  },
  methods: {
    getPhoneArea() {
      this.$http
        .get('/sys/params/page?page=1&limit=9999&paramCode=phoneNumber&paramType=1')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.phoneCodeList = res.data.list;
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    emailBlur(val) {
      this.isFocus = false;
    },
    emailFocus() {
      this.isClick = true;
      this.isFocus = true;
    },
    emailChange() {
      if (this.formModel.old_email_phone.length >= 4) {
        if (!this.formModel.old_email_phone.includes('@')) {
          this.isShowAreaCode = true;
        } else {
          this.isShowAreaCode = false;
        }
      } else {
        this.isShowAreaCode = false;
      }
    },
    fetchUserInfo() {
      const id = localStorage.getItem('user_id');
      this.$http
        .get(`/sys/user/${id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            if (this.caminho === 'email') {
              this.emailForm.old_email_phone = res.data.email;
              this.emailForm.email_phone = res.data.email;
            } else if (this.caminho === 'mobile') {
              this.emailForm.old_email_phone = res.data.mobile;
              this.emailForm.email_phone = res.data.mobile;
            }
            // this.formModel.email = res.data.email;
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    // 清除定时器等交互
    clerarAction() {
      this.isShow = false;
      this.count = 60;
      clearInterval(this.timer);
      this.timer = null;
      this.buttonName = this.$t('add.add026');
    },
    logOut() {
      this.$http
        .post('/open/logout')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          window.localStorage.removeItem('user_headUrl');
          window.localStorage.removeItem('user_realName');
          window.localStorage.removeItem('user_superAdmin');
          window.localStorage.removeItem('user_organizedRoleId');
          window.localStorage.removeItem('user_organizedType');
          window.localStorage.removeItem('user_roleId');
          window.localStorage.removeItem('user_jg_id');
          window.localStorage.removeItem('user_owner');
          window.localStorage.removeItem('user_permissionsList');
          window.localStorage.removeItem('user_id');
          window.localStorage.removeItem('user_name');
          window.localStorage.removeItem('user_roleId');
          window.localStorage.removeItem('user_organizedType');
          window.localStorage.removeItem('user_adminRoleName');
          window.localStorage.removeItem('tg_expand');
          // window.localStorage.removeItem('lang');
          Cookies.set('token', '', -1);

          this.$router.push('/');
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    substituirAccount() {
      let url = '';
      let formModel = {};
      let msg = '';
      if (this.caminho === 'mobile') {
        url = '/sys/user/bindPhone';
        formModel = {
          phone: this.formModel.email_phone,
          code: this.formModel.code,
        };
        msg = this.$t('personInfo.xinxi62');
      } else if (this.caminho === 'email') {
        url = '/sys/user/bindEmail';
        formModel = {
          email: this.formModel.email_phone,
          code: this.formModel.code,
        };
        msg = this.$t('personInfo.xinxi63');
      }
      this.$http
        .put(url, formModel)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.$message.success(this.$t('personInfo.xinxi50'));
            this.formModel = {
              old_email_phone: '',
              verificar_code: '',
              email_phone: '',
              code: '',
            };
            this.fetchUserInfo();
            clearInterval(this.timer);
            this.buttonName = this.$t('add.add026');
            this.count = 60;
            this.isShow = false;
            this.visible = false;
            this.$message.success(msg);
            this.logOut();
            this.$emit('success');
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    bindEmail() {
      if (this.currStep === '1') {
        // 校验手机号或者邮箱
        if (this.caminho === 'mobile') {
          let formData = new FormData();
          formData.append('phone', this.formModel.old_email_phone);
          formData.append('code', this.formModel.verificar_code);
          this.$http
            .post('/smsMessage/verify', formData)
            .then((res) => {
              if (res.data.code !== 0) {
                return this.$message.error(res.data.msg);
              } else {
                this.currStep = '2';
                this.clerarAction();
              }
            })
            .catch((e) => {
              console.error(e);
            });
        } else if (this.caminho === 'email') {
          // phoneOrEmail code
          this.$http
            .get(
              `/open/sms/verifyCode?phoneOrEmail=${this.formModel.old_email_phone}&code=${this.formModel.verificar_code}`,
            )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              } else {
                this.currStep = '2';
                this.clerarAction();
              }
            })
            .catch((err) => {
              console.log('err', err);
            });
        }
      } else if (this.currStep === '2') {
        if (this.caminho === 'mobile') {
          let formData = new FormData();
          formData.append('phone', this.formModel.email_phone);
          formData.append('code', this.formModel.code);
          this.$http
            .post('/smsMessage/verify', formData)
            .then((res) => {
              if (res.data.code !== 0) {
                return this.$message.error(res.data.msg);
              } else {
                this.substituirAccount();
                this.logOut();
              }
            })
            .catch((e) => {
              console.error(e);
            });
        } else {
          this.substituirAccount();
        }
      }
    },
    logOut() {
      this.$http
        .post('/open/logout')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          window.localStorage.removeItem('user_headUrl');
          window.localStorage.removeItem('user_realName');
          window.localStorage.removeItem('user_superAdmin');
          window.localStorage.removeItem('user_organizedRoleId');
          window.localStorage.removeItem('user_organizedType');
          window.localStorage.removeItem('user_roleId');
          window.localStorage.removeItem('user_jg_id');
          window.localStorage.removeItem('user_owner');
          window.localStorage.removeItem('user_permissionsList');
          window.localStorage.removeItem('user_id');
          window.localStorage.removeItem('user_name');
          window.localStorage.removeItem('user_roleId');
          window.localStorage.removeItem('user_organizedType');
          window.localStorage.removeItem('user_adminRoleName');
          window.localStorage.removeItem('tg_expand');
          // window.localStorage.removeItem('lang');
          Cookies.set('token', '', -1);

          this.$router.push('/');
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    onOpen() {
      this.fetchUserInfo();
    },
    onClose() {
      this.currStep = '1';
      this.formModel = {
        old_email_phone: this.old_email_phone,
        verificar_code: '',
        email_phone: '',
        code: '',
      };
      this.clerarAction();
    },
    // 封装一个发送验证码的方法
    sendCodeAction() {
      this.count = 60;
      this.isShow = true;
      this.timer = setInterval(() => {
        if (this.count > 0 && this.count <= 60) {
          this.count--;
          this.buttonName = this.count + this.$t('personInfo.xinxi48');
        } else {
          this.isShow = false;
          this.buttonName = this.$t('personInfo.xinxi49');
          this.clickCount = 0;
          clearInterval(this.timer);
          this.timer = undefined;
        }
      }, 1000);
    },
    // 获取验证码
    getValidCode() {
      // 这里区分一下
      if (this.caminho === 'mobile') {
        if (this.currStep === '1') {
          if (!isMobile(this.formModel.old_email_phone)) {
            return this.$message.error(this.$t('login.mima14'));
          }
        } else if (this.currStep === '2') {
          if (!isMobile(this.formModel.email_phone)) {
            return this.$message.error(this.$t('login.mima14'));
          }
        }
        this.clickCount++;
        if (this.clickCount !== 1) {
          return false;
        }
        let formData = new FormData();
        if (this.currStep === '1') {
          formData.append('phone', this.formModel.old_email_phone);
        } else if (this.currStep === '2') {
          formData.append('phone', this.formModel.email_phone);
        }

        this.$http
          .post('/smsMessage/send', formData)
          .then((res) => {
            if (res.data.code !== 0) {
              this.clickCount = 0;
              return this.$message.error(res.data.msg);
            } else {
              this.$message.success(this.$t('zhuce.zhuce36'));
              this.sendCodeAction();
            }
          })
          .catch((e) => {
            this.clickCount = 0;
            console.error(e);
          });
      } else if (this.caminho === 'email') {
        let uniqueKey = '';
        if (this.currStep === '1') {
          uniqueKey = this.formModel.old_email_phone;
          if (!isEmail(this.formModel.old_email_phone)) {
            return this.$message.error(this.$t('personInfo.xinxi47'));
          }
        } else if (this.currStep === '2') {
          uniqueKey = this.formModel.email_phone;
          if (!isEmail(this.formModel.email_phone)) {
            return this.$message.error(this.$t('personInfo.xinxi47'));
          }
        }
        this.clickCount++;
        if (this.clickCount !== 1) {
          return false;
        }
        this.$http
          .get(`/open/sms/sendSms?uniqueKey=${uniqueKey}&type=BIND_EMAIL`)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              this.clickCount = 0;
              return this.$message.error(res.msg);
            } else {
              // this.dataForm.code = res.data
              this.$message.success(this.$t('personInfo.xinxi57'));
              this.sendCodeAction();
            }
          })
          .catch((err) => {
            this.clickCount = 0;
            console.log('err', err);
          });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .change-bind-email-dialog {
  .el-form-item__content {
    margin-left: 0px !important;
    width: calc(100% - 80px) !important;
  }
  .formItem_code {
    position: relative;
    display: flex;

    .code_btn {
      height: 40px;
      line-height: 40px;
      position: absolute;
      right: 18px;
      //top: 2px;
      //color: #003e67;
      cursor: pointer;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      //line-height: 25px;
      color: #003e67;
    }
  }
  .form_box {
    margin-top: 20px;
    .phone_item {
      .el-form-item__content {
        margin-left: 80px !important;
      }
    }
  }
}
</style>
